import { useState } from 'react';
import apiClient from '../api/axios'; // 1. 引入apiClient
import { useNavigate, Link } from 'react-router-dom'; // 2. 引入useNavigate用于跳转

function RegisterPage() {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
  });
  const [error, setError] = useState('');
  const navigate = useNavigate(); // 3. 获取navigate函数

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => { // 4. 将函数改为async
    e.preventDefault();
    setError(''); // 清空之前的错误信息
    try {
      // 5. 使用apiClient发送POST请求
      const response = await apiClient.post('/users/register', formData);
      console.log('注册成功:', response.data);
      // 检查响应数据是否存在
      if (response && response.data) {
        // 6. 注册成功后跳转到登录页
        navigate('/login');
      } else {
        setError('注册响应数据格式错误');
      }
    } catch (err) {
      console.error('注册失败:', err.response?.data || err.message);
      // 更安全的错误处理
      const errorMsg = err.response?.data?.msg || err.message || '注册失败，请稍后再试';
      setError(errorMsg); // 7. 显示错误信息
    }
  };

  return (
    <div style={{ 
      maxWidth: '450px', 
      margin: '50px auto', 
      padding: '30px',
      backgroundColor: '#fff',
      borderRadius: '8px',
      boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)'
    }}>
      <h1 style={{ 
        textAlign: 'center', 
        marginBottom: '30px',
        color: '#333'
      }}>
        📝 用户注册
      </h1>
      
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '20px' }}>
          <label style={{ 
            display: 'block', 
            marginBottom: '8px',
            fontWeight: 'bold'
          }}>
            👤 用户名:
          </label>
          <input 
            name="username" 
            type="text" 
            value={formData.username} 
            onChange={handleChange} 
            placeholder="请输入用户名" 
            required 
            style={{ 
              width: '100%', 
              padding: '12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              fontSize: '16px',
              boxSizing: 'border-box'
            }}
          />
        </div>
        
        <div style={{ marginBottom: '20px' }}>
          <label style={{ 
            display: 'block', 
            marginBottom: '8px',
            fontWeight: 'bold'
          }}>
            📧 邮箱:
          </label>
          <input 
            name="email" 
            type="email" 
            value={formData.email} 
            onChange={handleChange} 
            placeholder="请输入邮箱" 
            required 
            style={{ 
              width: '100%', 
              padding: '12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              fontSize: '16px',
              boxSizing: 'border-box'
            }}
          />
        </div>
        
        <div style={{ marginBottom: '20px' }}>
          <label style={{ 
            display: 'block', 
            marginBottom: '8px',
            fontWeight: 'bold'
          }}>
            🔑 密码:
          </label>
          <input 
            name="password" 
            type="password" 
            value={formData.password} 
            onChange={handleChange} 
            placeholder="请输入密码" 
            required 
            style={{ 
              width: '100%', 
              padding: '12px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              fontSize: '16px',
              boxSizing: 'border-box'
            }}
          />
        </div>
        
        <button 
          type="submit" 
          style={{ 
            width: '100%', 
            padding: '12px', 
            backgroundColor: '#28a745', 
            color: 'white', 
            border: 'none', 
            borderRadius: '4px', 
            cursor: 'pointer',
            fontSize: '16px',
            fontWeight: 'bold'
          }}
        >
          🚀 注册
        </button>
      </form>
      
      <div style={{ 
        textAlign: 'center', 
        marginTop: '20px'
      }}>
        <p>
          已有账户？ 
          <Link to="/login" style={{ 
            color: '#007bff', 
            textDecoration: 'none',
            fontWeight: 'bold'
          }}>
            立即登录
          </Link>
        </p>
      </div>
      
      {error && <div style={{ 
        marginTop: '20px',
        padding: '12px',
        backgroundColor: '#f8d7da',
        color: '#721c24',
        border: '1px solid #f5c6cb',
        borderRadius: '4px',
        textAlign: 'center'
      }}>
        ❌ {error}
      </div>}
    </div>
  );
}
export default RegisterPage;